package org.example.javawebday1.utils;

import ch.qos.logback.core.util.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        if(StringUtil.isNullOrEmpty( token)){
            log.info("没有令牌");
            response.setStatus(401);
            response.sendRedirect("/login.html");
            return false;
        }

        try {
            JwtUtils.parseToken( token);
        }catch (Exception e)
        {
            log.info("令牌错误");
            response.setStatus(401);
            response.sendRedirect("/login.html");
            return false;
        }
        log.info("令牌可行，放行");
        return true;
    }
}
